package com.nec.recommend.module.weapp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.nec.recommend.auth.AuthUser;
import com.nec.recommend.auth.WeappProp;
import com.nec.recommend.consts.CacheGroupConst;
import com.nec.recommend.consts.TokenConst;
import com.nec.recommend.module.system.dto.TokenInfoDTO;
import com.nec.recommend.module.weapp.entity.WeappLoginResult;
import com.nec.recommend.module.weapp.entity.WeappUser;
import com.nec.recommend.module.weapp.service.WeappLoginService;
import com.nec.recommend.module.weapp.service.WeappUserService;
import com.nec.recommend.module.weapp.vo.WeappLoginVO;
import com.nec.recommend.utils.WeappUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class WeappLoginServiceImpl implements WeappLoginService {
    @Autowired
    private WeappProp weappProp;
    @Autowired
    private WeappUserService weappUserService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public TokenInfoDTO login(String code) {
        WeappLoginVO weappLoginVO = new WeappLoginVO();
        weappLoginVO.setAppid(weappProp.getAppid());
        weappLoginVO.setSecret(weappProp.getSecret());
        weappLoginVO.setJs_code(code);
        WeappLoginResult loginResult = WeappUtil.login(weappLoginVO);
        String openid = loginResult.getOpenid();
        WeappUser weappUser = weappUserService.lambdaQuery().eq(WeappUser::getOpenid, openid).one();
        if (Objects.isNull(weappUser)) {
            // 用户不存在，创建用户
            weappUser = WeappUser.buildDefault();
            weappUser.setOpenid(openid);
            weappUserService.save(weappUser);
        }
        String sessionKey = loginResult.getSession_key();
        // 保存用户会话信息
        AuthUser authUser = BeanUtil.copyProperties(weappUser, AuthUser.class);
        authUser.setToken(sessionKey);
        redisTemplate.opsForValue().set(CacheGroupConst.WEAPP_USER_SESSION + sessionKey, authUser, TokenConst.TOKEN_EXPIRE, TokenConst.EXPIRE_UNIT);
        return new TokenInfoDTO(TokenConst.WEAPP + TokenConst.TOKEN_HEADER, TokenConst.TOKEN_PREFIX + sessionKey);
    }
}
